package iterators;

import util.HtmlTextFinder;

//This iterator class returns value of html tag next to closest tag with one
//of names given by. mainly used in FirstParser,YNetParser, NRGParser 
public class AdvIterator extends NadlanIterator{
	protected int lastType;//last Type found in horizontal table
	
	public AdvIterator(String buf){this(buf,true);}	
	protected AdvIterator(String buf,boolean bFind)
	{
		super(buf,false);
		lastType=-10;
		if(bFind)
			findTitle();
	}

	public boolean hasNext()
	{
		bLast=!super.hasNext();
		if(bLast && curType>=0)
			return true;
		else
			return !bLast;
	}	
		
	//	Returns last value read and find next value and title 
	public Object next()
	{	
		String str=(curValue==null) ? new String(" ") : new String(curValue);
		if(!bLast)
			findTitle();
		else
			curType=-1;
		return str;
	};

	protected String findTitle()
	{	    		    	    
		//Look for one of advertisment data types
		if(lastType==-10)
		{
			while(hasNext() && (curType=txtFinder.getType(0))<0);					
			if(curType<0)
			{
				bLast=true;
				curValue=null;
				return null;
			};
			lastType=curType;
		}
		
		int lastPos=txtFinder.getPos();		
				
		//search for next data type string
		while(hasNext() && (curType=txtFinder.getType())<0);
		
		//if data table orientation is horizontal, then value is
		//before next data taype. Search for Data
		HtmlTextFinder it=
			new HtmlTextFinder(
					txtFinder.substring(lastPos,txtFinder.getValPos()-1));
		
		curValue=null;		
		while(it.hasNext())
		{ 
			curValue=it.getHtmlText();
			if(curValue!=null)
				break;
		}
		
		//Value found is before curType and after lastType and belongs to lastT
		//When swap between lasType and curType, to return correct type and to
		//save type found untill next findTitle call
		lastPos=curType;
		curType=lastType;
		lastType=lastPos;
		
		if(curValue!=null && it.getTypeOf(curValue)>=0)
			curValue=null;
		return curValue;
	}
	
}

